/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.expert.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.dto.ActivityQueryCriteria;
import com.fzhucc.modules.expert.domain.Expert;
import com.fzhucc.modules.expert.domain.ExpertMsgBox;
import com.fzhucc.modules.expert.domain.dto.ExpertBoxSeekDto;
import com.fzhucc.modules.expert.domain.dto.ExpertMsgBoxDto;
import com.fzhucc.modules.expert.domain.dto.ExpertMsgBoxQueryCriteria;
import com.fzhucc.modules.expert.domain.dto.ExpertQueryCriteria;
import com.fzhucc.modules.expert.repository.ExpertMsgBoxRepository;
import com.fzhucc.modules.expert.repository.ExpertRepository;
import com.fzhucc.modules.expert.service.mapstruct.ExpertMsgBoxMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-03-10
 **/
@Service
@RequiredArgsConstructor
public class ExpertMsgBoxService {

    private final ExpertMsgBoxRepository expertMsgBoxRepository;

    private final ExpertRepository expertRepository;
    private final ExpertMsgBoxMapper expertMsgBoxMapper;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    public Map<String, Object> queryAll(ExpertMsgBoxQueryCriteria criteria, Pageable pageable) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<ExpertMsgBox> page = expertMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<ExpertMsgBoxDto> map = page.map(expertMsgBoxMapper::toDto);
        List<ExpertMsgBoxDto> list = map.getContent();
        if (list != null) {
            for (ExpertMsgBoxDto expertMsgBoxDto : list) {
                Optional<Expert> res = expertRepository.findById(expertMsgBoxDto.getExpertId());
                if (res.isPresent()) {
                    expertMsgBoxDto.setExpert(res.get());
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(ExpertMsgBoxQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    public List<ExpertMsgBoxDto> queryAll(ExpertMsgBoxQueryCriteria criteria) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return expertMsgBoxMapper.toDto(expertMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public ExpertMsgBoxDto findById(Integer id) {
        ExpertMsgBox expertMsgBox = expertMsgBoxRepository.findById(id).orElseGet(ExpertMsgBox::new);
        ValidationUtil.isNull(expertMsgBox.getId(), "ExpertMsgBox", "id", id);
        return expertMsgBoxMapper.toDto(expertMsgBox);
    }

    @Transactional(rollbackFor = Exception.class)
    public ExpertMsgBoxDto create(ExpertMsgBox resources) {
        return expertMsgBoxMapper.toDto(expertMsgBoxRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ExpertMsgBox resources) {
        ExpertMsgBox expertMsgBox = expertMsgBoxRepository.findById(resources.getId()).orElseGet(ExpertMsgBox::new);
        ValidationUtil.isNull(expertMsgBox.getId(), "ExpertMsgBox", "id", resources.getId());
        expertMsgBox.copy(resources);
        expertMsgBoxRepository.save(expertMsgBox);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            expertMsgBoxRepository.deleteById(id);
        }
    }

    public ExpertMsgBoxDto seek(ExpertBoxSeekDto resources) {
        ExpertMsgBox expertMsgBox = new ExpertMsgBox();
        Optional<Expert> res = expertRepository.findById(resources.getExpertId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到该专家");
        }
        expertMsgBox.setExpertId(resources.getExpertId());
        expertMsgBox.setPhone(resources.getPhone());
        expertMsgBox.setConsultationTime(new Timestamp(new Date().getTime()));
        expertMsgBox.setContent(resources.getContent());
        expertMsgBox.setName(resources.getName());
        expertMsgBox.setOrgArea(res.get().getOrgArea());//专家的区域
        ExpertMsgBox expertMsgBox1 = expertMsgBoxRepository.save(expertMsgBox);
        return expertMsgBoxMapper.toDto(expertMsgBox1);
    }

    public void download(List<ExpertMsgBoxDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ExpertMsgBoxDto expertMsgBox : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("被咨询的专家id", expertMsgBox.getExpertId());
            map.put("咨询内容", expertMsgBox.getContent());
            map.put("联系方式", expertMsgBox.getPhone());
            map.put("咨询时间", expertMsgBox.getConsultationTime());
            map.put("咨询人姓名", expertMsgBox.getName());
            map.put("区域划分", expertMsgBox.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}